import Mock from 'mockjs'
import info from './info'
Mock.setup({
  timeout: '200-600'
})

// 生成token
const timeString = new Date()
const token = 'token' + timeString.getTime()
// 全局去判断token过期时间
function DetectToken(userToken) {
  const times = userToken.split('token')[1]
  console.log(times, 'times')
  // 超过10分钟token失效
  if (timeString.getTime() - times < 600000) {
    return {
      status: 0,
      msg: 'token正确'
    }
  } else {
    return {
      status: 1,
      msg: 'token错误'
    }
  }
}

// 登录
Mock.mock('api/login', 'post', data => {
  const updata = JSON.parse(data.body)
  console.log(updata, '请求')
  // 遍历查看是否有当前用户
  const userinfo = info.userlist.filter(item => item.name === updata.params.username && item.passwold === updata.params.passwold)
  if (userinfo.length) {
    return {
      token: token,
      status: 0,
      msg: '登录成功'
    }
  } else {
    return {
      status: 1,
      msg: '登录失败'
    }
  }
})
// 获取用户信息
Mock.mock('api/useinfo', 'post', data => {
  const updata = JSON.parse(data.body)
  console.log(data, updata, '请求')

  if (DetectToken(updata.params.token).status === 1) {
    return {
      status: 1,
      msg: 'token失效'
    }
  }
  const userinfo = info.useinfo.filter(item => item.name === updata.params.username)
  if (userinfo.length) {
    return {
      data: userinfo[0],
      status: 0,
      msg: '获取成功'
    }
  } else {
    return {
      status: 1,
      msg: '登录信息失败，请重新登录'
    }
  }
}
)
